package com.lemon.exam.common.filter;

import com.alibaba.fastjson2.JSON;
import com.lemon.exam.common.constant.RedisKeyConst;
import com.lemon.exam.common.entity.dto.LoginDTO;
import com.lemon.exam.common.entity.system.LoginUser;
import com.lemon.exam.common.exception.CustomException;
import com.lemon.exam.common.properties.ConfigProperties;
import com.lemon.exam.common.redis.RedisService;
import com.lemon.exam.common.util.*;
import jakarta.annotation.Resource;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 登录过滤器
 *
 * @author Lemon
 * @since 2025/3/24 14:04
 */
@Slf4j
@Component
public class LoginWebFilter implements WebFilter {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private ReactiveAuthenticationManager authenticationManager;
    @Resource
    private RedisService redisService;
    @Resource
    private ConfigProperties configProperties;
    @Resource
    private DatabaseClient databaseClient;
    @Resource
    private Validator validator;

    @Override
    @NonNull
    public Mono<Void> filter(ServerWebExchange exchange, @NonNull WebFilterChain chain) {
        // 非登录路径直接放行
        if (!isLoginPath(exchange.getRequest())) {
            return chain.filter(exchange);
        }
        return handleLoginRequest(exchange.getRequest(), exchange.getResponse(), RequestUtil.getClientIp(exchange.getRequest()));
    }

    /**
     * 判断是否为登录路径
     *
     * @param request
     * @return
     */
    private boolean isLoginPath(ServerHttpRequest request) {
        return configProperties.getJwt().getLoginPath().equals(request.getPath().value());
    }

    /**
     * 处理登录请求
     *
     * @param request
     * @param response
     * @return
     */
    private Mono<Void> handleLoginRequest(ServerHttpRequest request, ServerHttpResponse response, String ip) {
        return extractLoginBody(request)
                .flatMap(param -> ValidatorUtil.validate(validator, param)
                        .then(checkLoginCount(ip))
                        .then(verifyCaptcha(request, param.code()))
                        .then(authenticateUser(param.username(), param.password()))
                        .flatMap(user -> processSuccessfulLogin(response, ip, user, param.password()))
                        .onErrorResume(error -> handleLoginError(response, error))
                )
                .switchIfEmpty(ResponseUtil.err(response, 400, "请求体不能为空"));
    }

    /**
     * 获取请求体数据
     *
     * @param request
     * @return
     */
    private Mono<LoginDTO> extractLoginBody(ServerHttpRequest request) {
        return request.getBody().next().flatMap(dataBuffer -> {
            byte[] bytes = new byte[dataBuffer.readableByteCount()];
            dataBuffer.read(bytes);
            try {
                LoginDTO param = JSON.parseObject(new String(bytes), LoginDTO.class);
                //密码解密
                String password = RsaUtil.getInstance().decryptByPrivateKey(configProperties.getRsa().getPrivateKey(), param.password());
                return Mono.just(new LoginDTO(param.username(), password, param.code()));
            } catch (Exception e) {
                return Mono.error(new CustomException(400, "请求体格式错误"));
            }
        });
    }

    /**
     * 检查登录次数
     *
     * @param ip
     * @return
     */
    private Mono<Boolean> checkLoginCount(String ip) {
        String key = RedisKeyConst.LOGIN_USER_COUNT + ip;
        return redisService.string().increment(key, 1).flatMap(count -> {
            if (count > 5) {
                return Mono.error(new CustomException(429, "尝试次数过多，请稍后再试"));
            } else {
                return redisService.string().expire(key, Duration.ofMinutes(15));
            }
        });
    }

    /**
     * 验证验证码
     *
     * @param request
     * @param code
     * @return
     */
    private Mono<Void> verifyCaptcha(ServerHttpRequest request, String code) {
        String uuid = request.getHeaders().getFirst("uuid");
        if (!StringUtils.hasText(uuid)) {
            return Mono.error(new CustomException(402, "验证码标识不能为空"));
        }

        return redisService.string().get(RedisKeyConst.LOGIN_USER_CAPTCHA + uuid, String.class)
                .switchIfEmpty(Mono.error(new CustomException(402, "验证码已过期")))
                .filter(storedCode -> storedCode.equalsIgnoreCase(code))
                .switchIfEmpty(Mono.error(new CustomException(402, "验证码错误")))
                .flatMap(storedCode -> redisService.string().del(RedisKeyConst.LOGIN_USER_CAPTCHA + uuid))
                .then();
    }

    /**
     * 认证用户
     *
     * @param username
     * @param password
     * @return
     */
    private Mono<LoginUser> authenticateUser(String username, String password) {
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))
                .map(auth -> (LoginUser) auth.getPrincipal());
    }

    /**
     * 登录成功的处理
     *
     * @param response
     * @param ip
     * @param user
     * @return
     */
    private Mono<Void> processSuccessfulLogin(ServerHttpResponse response, String ip, LoginUser user, String password) {
        return Mono.when(updateUserLoginInfo(user.getId(), ip), storeUserInRedis(user))
                .then(generateAndSetTokens(response, user.getUsername(), password))
                .then(ResponseUtil.ok(response, "登录成功"));
    }

    private static final String UPDATE_IP_AND_LOGIN_TIME_SQL = """
            UPDATE sys_user SET
            prev_login_ip = IF(prev_login_ip IS NULL, :ip, CONCAT(SUBSTRING_INDEX(SUBSTRING_INDEX(prev_login_ip, ',', 2), ',', -1),',', :ip)),
            prev_login_time = IF(prev_login_time IS NULL, NOW(), CONCAT(SUBSTRING_INDEX(SUBSTRING_INDEX(prev_login_time, ',', 2), ',', -1),',', NOW()))
            WHERE id = :id
            """;

    /**
     * 修改用户信息
     *
     * @param userId
     * @param ip
     * @return
     */
    private Mono<Void> updateUserLoginInfo(Long userId, String ip) {
        return databaseClient.sql(UPDATE_IP_AND_LOGIN_TIME_SQL)
                .bind("ip", ip)
                .bind("id", userId)
                .fetch()
                .rowsUpdated()
                .filter(count -> count == 1)
                .switchIfEmpty(Mono.error(new CustomException(500, "用户登录信息更新失败")))
                .then(Mono.empty());
    }

    /**
     * 把用户信息存入 Redis
     *
     * @param user
     * @return
     */
    private Mono<Boolean> storeUserInRedis(LoginUser user) {
        return redisService.hash().del(RedisKeyConst.LOGIN_USER, user.getUsername())
                .then(redisService.hash().put(RedisKeyConst.LOGIN_USER, user.getUsername(), user))
                .filter(Boolean.TRUE::equals)
                .switchIfEmpty(Mono.error(new CustomException(500, "用户信息存储失败")));
    }

    /**
     * 生成并设置token
     *
     * @param response
     * @param username
     * @param password
     * @return
     */
    private Mono<Void> generateAndSetTokens(ServerHttpResponse response, String username, String password) {
        //1.生成token
        String token = jwtUtil.generateAccessToken(username);
        //2.密码公钥加密
        String encrypt = RsaUtil.getInstance().encryptByPublicKey(configProperties.getRsa().getPublicKey(), password);
        //3.生成refreshToken
        String refreshToken = jwtUtil.generateRefreshToken(username, encrypt);
        //4.设置token到响应头中
        response.getHeaders().add(HttpHeaders.AUTHORIZATION, configProperties.getJwt().getAccessTokenPrefix() + token);
        response.getHeaders().add(configProperties.getJwt().getRefreshTokenHeader(), configProperties.getJwt().getRefreshTokenPrefix() + refreshToken);

        return Mono.empty();
    }

    /**
     * 登录失败的处理
     *
     * @param response
     * @param error
     * @return
     */
    private Mono<Void> handleLoginError(ServerHttpResponse response, Throwable error) {
        if (error instanceof CustomException e) {
            return ResponseUtil.err(response, e.getCode(), e.getMessage());
        }
        log.error("登录处理异常", error);
        return ResponseUtil.err(response, 500, "系统异常");
    }
}
